package com.kyrie.lib_sys.application.borrowApplys.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kyrie.lib_sys.common.entity.PageResult;
import com.kyrie.lib_sys.common.pojo.dto.BorrowDTO;
import com.kyrie.lib_sys.common.pojo.dto.BorrowPageQueryDTO;
import com.kyrie.lib_sys.common.pojo.entity.Borrow;
import com.kyrie.lib_sys.application.borrowApplys.mapper.BorrowMapper;
import com.kyrie.lib_sys.application.borrowApplys.service.BorrowService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 借阅service类
 *
 * @author heefM
 * @date 2025-08-09
 */
@Service
public class BorrowServiceImpl implements BorrowService {
    @Autowired
    private BorrowMapper borrowMapper;

    /**
     * 添加借阅
     *
     * @param borrowDTO
     */
    @Override
    public void insert(BorrowDTO borrowDTO) {
        Borrow borrow = new Borrow();
        BeanUtils.copyProperties(borrowDTO, borrow);
        borrowMapper.insert(borrow);
    }

    /**
     * 查询借阅
     *
     * @param borrowDTO
     * @return
     */
    @Override
    public Borrow queryBorrow(BorrowDTO borrowDTO) {
        Borrow borrow = new Borrow();
        BeanUtils.copyProperties(borrowDTO, borrow);
        return borrowMapper.queryByCondition(borrow);
    }

    /**
     * 查询借阅列表
     *
     * @param borrowPageQueryDTO
     * @return
     */
    @Override
    public PageResult queryPage(BorrowPageQueryDTO borrowPageQueryDTO) {
        PageHelper.startPage(borrowPageQueryDTO.getPageNum(), borrowPageQueryDTO.getPageSize());
        Page<Borrow> page = borrowMapper.queryList(borrowPageQueryDTO);
        PageResult pageResult = new PageResult(page.getTotal(), page);
        return pageResult;
    }

    /**
     * 修改借阅
     *
     * @param borrowDTO
     */
    @Override
    public void update(BorrowDTO borrowDTO) {
        Borrow borrow = new Borrow();
        BeanUtils.copyProperties(borrowDTO, borrow);
        borrowMapper.update(borrow);
    }

    /**
     * 删除借阅
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        borrowMapper.deleteById(id);
    }

    /**
     * 批量删除借阅
     *
     * @param ids
     */
    @Override
    public void deleteBatch(List<Long> ids) {
        borrowMapper.deleteBatch(ids);
    }

    /**
     * 批量添加借阅
     *
     * @param borrowDTOS
     */
    @Override
    public void insertBatch(List<BorrowDTO> borrowDTOS) {
        List<Borrow> borrowList = borrowDTOS.stream().map(borrowDTO -> {
            Borrow borrow = new Borrow();
            BeanUtils.copyProperties(borrowDTO, borrow);
            return borrow;
        }).toList();
        borrowMapper.insertBatch(borrowList);
    }

    /**
     * 图书借阅信息导出
     * @param response
     * @throws IOException
     */
    @Override
    public void excelPort(HttpServletResponse response) throws IOException {
        // 1. 创建Workbook
        Workbook workbook = new XSSFWorkbook(); // 生成.xlsx

        // 2. 创建Sheet、Row、Cell，并填充数据
        Sheet sheet = workbook.createSheet("借阅记录");

        // 添加报表标题
        Row titleRow = sheet.createRow(0);
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellValue("图书借阅报表");
        // 设置标题单元格样式（可选）
        titleCell.setCellStyle(workbook.createCellStyle());
        titleCell.getCellStyle().setAlignment(HorizontalAlignment.CENTER);
        titleCell.getCellStyle().setVerticalAlignment(VerticalAlignment.CENTER);

        // 添加表头
        Row headerRow = sheet.createRow(1);
        headerRow.createCell(0).setCellValue("借阅ID");
        headerRow.createCell(1).setCellValue("借阅用户id");
        headerRow.createCell(2).setCellValue("借阅图书id");
        headerRow.createCell(3).setCellValue("借阅日期");
        headerRow.createCell(4).setCellValue("归还日期");
        headerRow.createCell(5).setCellValue("实际归还日期");
        headerRow.createCell(6).setCellValue("借阅状态(0/1/2/3)");
        headerRow.createCell(7).setCellValue("备注");
        headerRow.createCell(8).setCellValue("创建时间");
        headerRow.createCell(9).setCellValue("更新时间");

        // 3. 获取借阅列表数据
        List<Borrow> borrowList = borrowMapper.queryList(null); // 使用Mapper查询全部借阅记录

        // 4. 填充数据行
        int rowNum = 2; // 从第2行开始填充数据（第0行是标题，第1行是表头）
        for (Borrow borrow : borrowList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(borrow.getId());//借阅ID
            row.createCell(1).setCellValue(borrow.getUserId());//借阅用户id
            row.createCell(2).setCellValue(borrow.getBookId());//借阅图书id

            // 处理借阅日期
            if (borrow.getBorrowDate() != null) {
                row.createCell(3).setCellValue(formatDate(borrow.getBorrowDate()));//借阅日期
            }

            // 处理归还日期
            if (borrow.getDueDate() != null) {
                row.createCell(4).setCellValue(formatDate(borrow.getDueDate()));//归还日期
            }

            // 处理实际归还日期
            if (borrow.getReturnDate() != null) {
                row.createCell(5).setCellValue(formatDate(borrow.getReturnDate()));//实际归还日期
            }

            row.createCell(6).setCellValue(borrow.getStatus());//借阅状态(0/1/2/3)
            row.createCell(7).setCellValue(borrow.getRemark());//备注

            // 处理创建时间
            if (borrow.getCreateTime() != null) {
                row.createCell(8).setCellValue(formatDate(borrow.getCreateTime()));//创建时间
            }

            // 处理更新时间
            if (borrow.getUpdateTime() != null) {
                row.createCell(9).setCellValue(formatDate(borrow.getUpdateTime()));//更新时间
            }
        }

        // 5. 关键步骤：获取Response的输出流，并将Workbook写入
        //    使用 try-with-resources 确保workbook关闭，关闭workbook也会自动关闭outputStream
        try (workbook; ServletOutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
            outputStream.flush();
        } // try-with-resources 会自动关闭资源
        catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 格式化日期为 yyyy.mm.dd 格式
     */
    private String formatDate(Date date) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        return sdf.format(date);
    }


}
